<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: inc.dotips.php 1126 2008-06-09 05:45:04Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 
      if(!$my->id){
          
          require(getTemplateFile(JL_TEMPLATE_PATH, 'user_login.tpl.php'));
      }

// Anmeldung Ende
//##########################################################################################################################

      
//##########################################################################################################################
// Ist der User angemeldet, kann er seine Tipps abgeben
      
      else {
        
        if(isset($_POST["register"])){
          $member = new TipMember($database);
          $member->save($_POST, false);
          $query="SELECT picture FROM #__joomleague_tip_members WHERE user_id=".$my->id." AND picture IS NOT NULL LIMIT 1";
          $database->setQuery($query);
        	if ($picture = $database->loadResult()) {
        		$query="UPDATE #__joomleague_tip_members SET picture = '".$picture."' WHERE user_id = ".$my->id;
        		$database->setQuery($query);
        		$database->query();
        	}
        }
        
        $query = sprintf("SELECT count(user_id) FROM #__joomleague_tip_members
                           WHERE project_id = %s AND user_id = %s", $joomleague->id, $my->id);
        $database->setQuery($query);
        $registered = $database->loadResult();

        if(($registered) || ($user_is_tippadmin == 1 && ($usetipadmin==1))) {
          if (($user_is_tippadmin == 0) || ($usetipadmin==0)) $user_id = $my->id; else $user_id = $uid;
          
          $query = sprintf("SELECT count(user_id) FROM #__joomleague_tip_members
                           WHERE project_id = %s AND user_id = %s and approved", $joomleague->id, $user_id);
          $database->setQuery($query);
          $approved = $database->loadResult();
/*****
            $query = sprintf("SELECT count(user_id) FROM #__joomleague_tip_members
                               WHERE project_id = %s AND user_id = %s and approved and tipadmin", $joomleague->id, $user_id);
            $database->setQuery($query);
            $usertipadmin = $database->loadResult();                
          } else $usertipadmin = 1;
******/
          // BAD vulneralble: $round = (intval(mosGetParam($_REQUEST, 'r', '0')) == 0) ? $joomleague->current_round : $_REQUEST["r"];
          $round = ($r == 0) ? $joomleague->current_round : $r;
          $rounds = $joomleague->getRoundNames();          
          
          if(($approved) || ($user_is_tippadmin == 1 && ($usetipadmin==1))) {
            
            if ($user_is_tippadmin == 1 && ($usetipadmin==1) && $user_id<>'') {
              $query = sprintf("SELECT count(user_id) FROM #__joomleague_tip_members
                                 WHERE project_id = %s AND user_id = %s and approved and tipadmin", $joomleague->id, $user_id);
              $database->setQuery($query);
              $usertipadmin = $database->loadResult();
              if ($usertipadmin==0) $user_id = 0;
            }
            foreach ($_POST AS $key => $value) {
             if ($key == 'joker') $tippsave[$key] = mosGetParam($_POST, "$key", ''); else if ($value!='') $tippsave[$key] = floatval(mosGetParam($_POST, "$key", NULL));
            }
            if(isset($tippsave["saveTips"])){
              
              $tip = new TipResult($database);
              $mailmessage = $tip->saveTips($cids, $tippsave, $joomleague, $usetipadmin, $user_is_tippadmin);
              $thistime=$joomleague->getTimestamp('');
              if ($user_is_tippadmin == 0 || ($usetipadmin==0)) {
	          	$query = sprintf("UPDATE #__joomleague_tip_members SET last_tip = '%s' WHERE (project_id = %s) AND (user_id = %s)", date('Y-m-d H:i:s',$thistime), $tippsave['p'], $tippsave['user_id']);
    	      	$database->setQuery($query);
        	  	$database->query();
        	  }
        	  $query="SELECT receipt FROM #__joomleague_tip_members WHERE project_id = ".$tippsave['p']." AND user_id = ".$tippsave['user_id'];
        	  $database->setQuery($query);
              $receipt = $database->loadResult();
        	  if (($showUser_config['edit_receipt'] == "1" && $receipt == 1) || ($user_is_tippadmin == 1)) {
          	    // Tippspiel Quittung per Mail START
        	  	$query = sprintf("SELECT email, name FROM #__users
                                   WHERE id = %s", $_POST['user_id']);
            	$database->setQuery($query);
                $tipuser = NULL;
              	$database->loadObject( $tipuser );
/*****
        	  	$query = sprintf("SELECT name FROM #__users
                                   WHERE id = %s", $_POST['user_id']);
            	$database->setQuery($query);
            	$name = $database->loadResult();            	
*****/
            	$thisdate = mosFormatDate(date('Y-m-d H:i:s', $thistime), _JL_MATCHDAYDATE." %H:%M");
            	$mailsubject = str_replace('$DATE$', $thisdate, trim($showUser_config['receipt_subject']));
            	$mailsubject = str_replace('$ROUND$', $tippsave['r'], $mailsubject);
            	$mailsubject = str_replace('$URL$', JLLIVEURL, $mailsubject);
            	
                $mailheader = str_replace('$DATE$', $thisdate, trim($showUser_config['receipt_intro']));
            	$mailheader = str_replace('$ROUND$', $tippsave['r'], $mailheader);
            	$mailheader = str_replace('$URL$', JLLIVEURL, $mailheader);
            	$mailheader = str_replace('$NL$', "\n", $mailheader);
            	$mailheader = str_replace('$DL$', "\n\n", $mailheader);
            	$mailheader = str_replace('$NAME$', $tipuser->name, $mailheader);
            	
            	$mailfooter = str_replace('$DATE$', $thisdate, trim($showUser_config['receipt_footer']));
            	$mailfooter = str_replace('$ROUND$', $tippsave['r'], $mailfooter);
            	$mailfooter = str_replace('$URL$', JLLIVEURL, $mailfooter);
            	$mailfooter = str_replace('$NL$', "\n", $mailfooter);
            	$mailfooter = str_replace('$DL$', "\n\n", $mailfooter);
            	
            	$newline="\n";
        	  	mosMail( $mosConfig_mailfrom, $mosConfig_fromname, $tipuser->email, $mailsubject, $mailheader.$newline.$mailmessage.$newline.$mailfooter, 0 );
        	  	// Tippspiel Quittung per Mail ENDE
        	
        	   }
             // Weiterleitung nach Tippabgabe
             if (isset($tippsave['r'])) $tippround="&amp;r=".$tippsave['r']; else $tippround='';
             header("Location: ".str_replace('&amp;','&',JL_COMPONENT_LINK."&amp;func=savedTips&amp;p=".$joomleague->id.$tippround.JL_ITEMID_SUFFIX));
             //Weiterleitung Ende
            }
          
            if ($user_id != '') $tempmy->id = $user_id; else $tempmy->id = $my->id;
            $tips = $joomleague->getTips($tempmy, $round);
            for ($x=0;$x<count($tips);$x++) {
              $query="SELECT COUNT(id) FROM #__joomleague_tip_results WHERE tip=0 AND match_id = ".$tips[$x]->match_id; 
              $database->setQuery($query);
              $unentschieden[$tips[$x]->match_id] = $database->loadResult();
              $query="SELECT COUNT(id) FROM #__joomleague_tip_results WHERE tip=1 AND match_id = ".$tips[$x]->match_id;
              $database->setQuery($query);
              $heimsiege[$tips[$x]->match_id] = $database->loadResult();
              $query="SELECT COUNT(id) FROM #__joomleague_tip_results WHERE tip=2 AND match_id = ".$tips[$x]->match_id;
              $database->setQuery($query);
              $auswaertssiege[$tips[$x]->match_id] = $database->loadResult();
            }
            
            $joker_allowed = 1;
            
            if ($joomleague->tip_joker_limit>0) {
               $query = sprintf("SELECT COUNT(joker) FROM #__joomleague_tip_results WHERE joker=1 AND project_id=%s AND user_id=%s", $joomleague->id, $user_id);
               $database->setQuery($query);
               $joker_count = $database->loadResult();
               if ($joker_count>=$joomleague->tip_joker_limit) $joker_allowed = 0;
            }

            $query = sprintf("SELECT COUNT(r.matchcode)
                                FROM #__joomleague_rounds r
                           LEFT JOIN #__joomleague_matches m ON m.round_id=r.id
                           LEFT JOIN #__joomleague_tip_results tr ON tr.match_id=m.match_id
                               WHERE tr.joker=1 AND tr.project_id=%s AND tr.user_id=%s AND r.matchcode=%s", $joomleague->id, $user_id, $round);
            $database->setQuery($query);
            $joker_set=$database->loadResult();
            if ($joker_set==1) $joker_allowed = 1;
            
			$pageNav=$joomleague->pagenav($jl_func,count($rounds), $round);
			$pageNav2=$joomleague->pagenav2($jl_func, count($rounds), $round);
			
			if ($usetipadmin==1) {
              $query = sprintf("SELECT tm.user_id, u.name 
                                  FROM #__joomleague_tip_members tm
                                  LEFT JOIN #__users u ON tm.user_id = u.id
                                 WHERE project_id = %s and approved and tipadmin", $joomleague->id);
              $database->setQuery($query);
              $userlist = $database->loadObjectList();
              $pageNav3='<form action="" method="get" style="display:inline;">';
              $pageNav3.='<select class="inputbox" onchange="joomleague_changedoc(this)">';
              $url=JL_COMPONENT_LINK."&amp;func=".$jl_func."&amp;p=".$joomleague->id;
              if ($round) $url .= "&amp;r=".$round;
              $url .= JL_ITEMID_SUFFIX;
              $pageNav3.="<option value='".sefRelToAbs($url)."'>"._JL_TIPS_SELECT_USER."</option>";
              foreach ($userlist as $var) {
                $pageNav3.="<option value='";
                $pageNav3.=sefRelToAbs($url.'&amp;uid='.$var->user_id)."'";
                if ($user_id==$var->user_id) { $pageNav3.=" selected='selected'"; }
                $pageNav3.=">";
                $pageNav3.=$var->name."</option>";
              }
              $pageNav3.='</select></form>';
            }

            $current_round=$round;
            require(getTemplateFile(JL_TEMPLATE_PATH, 'user_tips.tpl.php'));
          }

// Ende der Tippabgabe
//##########################################################################################################################


//##########################################################################################################################          
//Wenn der User noch nicht freigeschaltet ist, wird ein Hinweis ausgegeben

          else{
          

          require(getTemplateFile(JL_TEMPLATE_PATH, 'user_approve.tpl.php'));
          }
        }
        
// Warten auf Freischaltung Ende
//##########################################################################################################################


//##########################################################################################################################
//Wenn der User noch nicht registriert ist, wird der Registrierungsbutton angezeigt   
     
        else{
          
          
          require(getTemplateFile(JL_TEMPLATE_PATH, 'user_register.tpl.php'));
        } //registered
      } //my->id